package org.csc.sss.admin.config;

import org.csc.sss.admin.interceptor.HandlerInterceptor;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(new HandlerInterceptor()).addPathPatterns("/api/**");

    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //还可以设置更多
//        registry.addMapping("/**")//指定访问路径
//                .allowedOrigins("/**")//指定来自那个域名的跨域访问
//                .allowedMethods("POST", "GET");//指定方法是post、get
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        //指定所有的日期参数格式
        registry.addFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer (){
            @Override
            public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
                ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error404");
                ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error500");
                ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error403");
                configurableEmbeddedServletContainer.addErrorPages(errorPage404, errorPage500, errorPage403);
            }
        };
    }
}
